﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using skiordiecore;
using Perst;

namespace skiordie_gui
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
            db = StorageFactory.Instance.CreateStorage();

        }

        private Storage db;
        private Root root;
        private static SplashScreenForm splash;

        private void Form1_Load(object sender, EventArgs e)
        {
            // Create a new thread from which to start the splash screen form
            Thread splashThread = new Thread(new ThreadStart(StartSplash));
            splashThread.Start();

            // Pretend that our application is doing a bunch of loading and
            // initialization
            Thread.Sleep(7000 / 2);

            // Sit and spin while we wait for the minimum timer interval if
            // the interval has not already passed

            // Close the splash screen
            CloseSplash();

            this.BringToFront();
        }

        static public void StartSplash()
        {
            // Instance a splash form given the image names
            splash = new SplashScreenForm();

            // Run the form
            Application.Run(splash);
        }

        private void CloseSplash()
        {
            if (splash == null)
                return;

            // Shut down the splash screen
            splash.Invoke(new EventHandler(splash.KillMe));
            splash.Dispose();
            splash = null;
        }



        private void btnNewDb_Click(object sender, EventArgs e)
        {
            string path = String.Empty;

            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
               // Disconnect();
                path = saveFileDialog1.FileName;
                Connect(path);
            }
            else
            {
                return;
            }


        }


        private void Connect(string path)
        {

            try
            {
                db.Open(@path, 512);


                root = (Root)db.Root;

                if (root == null)
                {
                    root = new Root(db);
                    db.Root = root;
                }

                btnCloseDb.Enabled = true;
                tabControlMain.Enabled = true;
                btnOpenDb.Enabled = false;
                btnNewDb.Enabled = false;

                RefreshControls();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Wyjątek przy łaczeniu z bazą!");
            }

        }

        private void RefreshControls()
        {
            RefreshChampionships();
            RefreshParticipants();
        }

        private void Disconnect()
        {
            try
            {
                db.Close();
                root = null;

                btnCloseDb.Enabled = false;
                tabControlMain.Enabled = false;

                btnOpenDb.Enabled = true;
                btnNewDb.Enabled = true;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Wyjątek przy rozłaczeniu z bazą!");
            }
            finally
            {
                listViewParticipants.Items.Clear();
                listViewChampionships.Items.Clear();
                listViewChampPart.Items.Clear();
            }

        }

        public void AddChampionship(Championship c)
        {
            if (root != null)
            {

                root.intKeyIndex.Append(c);
                root.strKeyIndex.Put(c);

                RefreshChampionships();

            }

        }

        private void RefreshChampionships()
        {

            if (root != null)
            {
                listViewChampionships.Items.Clear();


                foreach (Championship c in root.intKeyIndex)
                {
                    // create the subitems to add to the list
                    string[] myItems = new string[] { c.name, c.eventDate.ToLocalTime().ToString() };
                    ListViewItem lvi = new ListViewItem(myItems);
                    lvi.Name = c.id.ToString();
                    // insert all the items into the listview at the last available row
                    listViewChampionships.Items.Add(lvi);

                }

            }

        }

        private void RefreshChampionshipParticipants(ListViewItem lvic)
        {

            if (root != null)
            {
                listViewChampPart.Items.Clear();

                //ListViewItem lvci = listViewChampionships.SelectedItems[0];


                Championship c = (Championship)root.intKeyIndex[Convert.ToInt32(lvic.Name)];

                if (c.Participants != null)
                {
                    foreach (Participant p in c.Participants)
                    {
                        // create the subitems to add to the list
                        string[] myItems = new string[] { p.firstName, p.lastName, p.birthDate.ToShortDateString() };
                        ListViewItem lvi = new ListViewItem(myItems);
                        lvi.Name = p.id.ToString();
                        // insert all the items into the listview at the last available row
                        listViewChampPart.Items.Add(lvi);

                    }
                }

            }

        }

        private void btnOpenDb_Click(object sender, EventArgs e)
        {
            string path = String.Empty;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                //Disconnect();
                path = openFileDialog1.FileName;
                Connect(path);
            }
            else
            {
                return;
            }
        }

        private void btnCloseDb_Click(object sender, EventArgs e)
        {
            Disconnect();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            ChampionshipForm f = new ChampionshipForm();


            if (f.ShowDialog() == DialogResult.OK)
            {
                AddChampionship(new Championship(f.name, f.eventDate));
            }

            f.Close();


        }


        private void button6_Click(object sender, EventArgs e)
        {

            if (root != null)
            {
                try
                {
                    ListViewItem lvi = listViewChampionships.SelectedItems[0];

                    Championship c = (Championship)root.intKeyIndex[Convert.ToInt32(lvi.Name)];

                    root.intKeyIndex.Remove(c);
                    root.strKeyIndex.Remove(c);

                    RefreshChampionships();


                }
                catch
                {
                    MessageBox.Show("Wybierz zawody do usunięcia", "Błąd!");
                }
            }

        }

        private void btnEditChampionship_Click(object sender, EventArgs e)
        {
            if (root != null)
            {
                try
                {
                    ListViewItem lvi = listViewChampionships.SelectedItems[0];

                    Championship c = (Championship)root.intKeyIndex[Convert.ToInt32(lvi.Name)];

                    ChampionshipForm f = new ChampionshipForm();

                    f.name = c.name;
                    f.eventDate = c.eventDate;
                    f.Tag = 1;

                    if (f.ShowDialog() == DialogResult.OK)
                    {
                        c.name = f.name;
                        c.eventDate = f.eventDate;
                        RefreshParticipants();
                    }

                    f.Close();



                }
                catch
                {
                    MessageBox.Show("Wybierz zawody do edytowania", "Błąd!");
                }
            }
        }

        private void tabControlMain_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void btnNewParticipant_Click(object sender, EventArgs e)
        {

            ParticipantForm f = new ParticipantForm();


            if (f.ShowDialog() == DialogResult.OK)
            {
                AddParticipant(new Participant(f.firstName, f.lastName, f.birthDate));
            }

            f.Close();

        }

        public void AddParticipant(Participant p)
        {
            if (root != null)
            {

                root.intKeyParticipants.Append(p);
                //root.intKeyParticipants.Put(p);

                RefreshParticipants();
            }

        }

        private void RefreshParticipants()
        {

            if (root != null)
            {
                listViewParticipants.Items.Clear();


                foreach (Participant p in root.intKeyParticipants)
                {
                    // create the subitems to add to the list
                    string[] myItems = new string[] { p.firstName, p.lastName, p.birthDate.ToShortDateString() };
                    ListViewItem lvi = new ListViewItem(myItems);
                    lvi.Name = p.id.ToString();
                    // insert all the items into the listview at the last available row
                    listViewParticipants.Items.Add(lvi);

                }

            }

        }

        private void btnEditParticipant_Click(object sender, EventArgs e)
        {
            if (root != null)
            {
                try
                {
                    ListViewItem lvi = listViewParticipants.SelectedItems[0];

                    Participant p = (Participant)root.intKeyParticipants[Convert.ToInt32(lvi.Name)];

                    ParticipantForm f = new ParticipantForm();

                    f.firstName = p.firstName;
                    f.lastName = p.lastName;
                    f.birthDate = p.birthDate;
                    f.Tag = 1;

                    if (f.ShowDialog() == DialogResult.OK)
                    {
                        p.firstName = f.firstName;
                        p.lastName = f.lastName;
                        p.birthDate = f.birthDate;
                        RefreshParticipants();
                    }

                    f.Close();



                }
                catch
                {
                    MessageBox.Show("Wybierz uczestnika do edytowania", "Błąd!");
                }
            }
        }



        private void btnDeleteParticipant_Click(object sender, EventArgs e)
        {

            if (root != null)
            {
                try
                {
                    ListViewItem lvi = listViewParticipants.SelectedItems[0];

                    Participant p = (Participant)root.intKeyParticipants[Convert.ToInt32(lvi.Name)];

                    root.intKeyParticipants.Remove(p);
                    root.intKeyParticipants.Remove(p);

                    RefreshParticipants();


                }
                catch
                {
                    MessageBox.Show("Wybierz zawodnika do usunięcia", "Błąd!");
                }
            }

        }

        private void btnAddPartToChamp_Click(object sender, EventArgs e)
        {

            if (root != null)
            {
                try
                {
                    ListViewItem lviChamp = listViewChampionships.SelectedItems[0];


                    //listViewParticipants.Items;

                    Championship c = (Championship)root.intKeyIndex[Convert.ToInt32(lviChamp.Name)];

                    AddParticipantForm f = new AddParticipantForm(root);

                    if (f.ShowDialog() == DialogResult.OK)
                    {

                        Participant p = (Participant)root.intKeyParticipants[Convert.ToInt32(f.name)];

                        root.intKeyIndex.Remove(c);
                        c.Deallocate();

                        c.AddParticipant(p);

                        root.intKeyIndex.Put(c);

                       // RefreshChampionshipParticipants(lviChamp);
                    }

                    f.Close();

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Wyjątek probie dodania uzytkownika!");
                    //  MessageBox.Show("Wybierz zawody do których chcesz dodac uczestnika", "Błąd!");
                }
            }

        }

        private void listViewChampionships_SelectedIndexChanged(object sender, EventArgs e)
        {
            RefreshChampionshipParticipants(listViewChampionships.SelectedItems[0]);
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            RefreshChampionshipParticipants(listViewChampionships.SelectedItems[0]);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }



    }
}
